//index.js
//获取应用实例
const http = require("../../utils/util.js");
var Crypto = require('../../utils/cryptojs/cryptojs.js').Crypto;
const app = getApp();
const recorderManager = wx.getRecorderManager();
const innerAudioContext = wx.createInnerAudioContext();
var tempFilePath;
Page({
  data: {
    houBaoStyle:1,
    userInfo:[],
    shuoming1:'小伙伴们说对口令就能获得随即打赏',
    shuoming2:'好友听完你说的话就能领取赏金',
    shuoming3:'好友念出你的答案就能领取赏金',
    kouling:'谢谢老板！', 
    Money:'',
    Number:'',
    answer:'',

    balance:[],   //余额
    // 录音动画；
    isSpeaking: false,
    speakerUrl: '../image/speaker0.png',
    speakerUrlPrefix: '../image/speaker',
    speakerUrlSuffix: '.png',

    voiceResult:false,
    clickHot:true,

    tempFilePath:'',
    formId:true,

    token:'',
    formId:'',
  },
  //事件处理函数
  ChangeTab:function(e){
    var that = this; 
    var currentTab = e.currentTarget.dataset.id;
    console.log(currentTab)
    that.setData({
      houBaoStyle: currentTab,
      Money: '',
      Number: '',
      answer: '',
      kouling:'',
    })
  },

  fromSubmit: function (e) {
    var that = this;
    var formId= e.detail.formId
    console.log(formId)
    that.setData({
      formId:formId,
    })
    that.toShare();
  },  
  fromReset:function(){
    console.log("from表单提交的更新")
  },
  onLoad: function () {
    var that = this;

    console.log(app.globalData.token)
    wx.getUserInfo({
      success:function(user){
        console.log(user)
        that.setData({
          userInfo:user.userInfo,
        })
      }
    })
    // 判断是否需要调用登陆；
    wx.getStorage({
      key: 'token',
      success: function (res) {
        console.log("获取token APP")
        console.log(res.data);
        var token = res.data;
        if (token == '' || token == undefined) {
          that.login();
        }else{
          that.setData({
            token:res.data,
          })
        }
      },
      fail: function (res) {
        console.log("获取toekn 失败")
        console.log(res)
        that.login();
      }
    })
  },
  onShow:function(){
    var that  = this;

    that.balance();
    // 获取access_token；
    // wx.request({
    //   url: "https://api.weixin.qq.com/cgi-bin/token",
    //   method:"GET",
    //   data:{
    //     grant_type: 'client_credential',
    //     appid:"wxc8bd87a140039008",
    //     secret:"5238da1f08605d19d7e007a81b3d0417",
    //   },
    //   success:function(res){
    //     console.log("获取access_token")
    //     console.log(res)
    //   },

    // })

  
  },
  // 登陆
  login: function () {
    var that = this;
    console.log("执行login")
    wx.login({
      success: res => {
        console.log(res)
        var user;
        wx.getUserInfo({
          success: function (user) {
            console.log("执行getCode")
            user = user;
            wx.request({
              url: app.globalData.localApi + "/user/getCode",
              method: "get",
              data: {
                code: res.code,
                userInfo: user.userInfo,
              },
              success: function (res) {
                console.log(res)
                wx.setStorage({
                  key: 'token',
                  data: res.data.data.token,
                })
                wx.getUserInfo({
                  success: function (user) {
                    console.log(user)
                    that.setData({
                      userInfo: user.userInfo,
                    })
                  }
                })

                that.balance();
              },
              fail: function (res) {
                that.showInfo("获取用户信息失败")
              }
            })
          }
        })
        console.log(res)
        console.log(res.code);
      }
    })
  },
  // 请求余额
  balance: function () {
    var that = this;
    wx.getStorage({
      key: 'token',
      success: function (res) {
        var token = res.data;
        var timestamp = app.timestamp();
        var url = app.globalData.localApi + "/user/balance";
        var data = {
          timestamp: timestamp,
          token: token,
          sign: Crypto.MD5(app.sign(url, token, timestamp)),
          url: app.urlStr(url),
        };
        wx.request({
          url: url,
          method: "POST",
          data: data,
          success: function (res) {
            console.log(res.data)
            if(res.data.code==201){
              app.login();
            }

            that.setData({
              balance:res.data.data,
            })
          },
        })
      },
    })
  },
// 口令红白生成
  // 获取语音
  startVoice: function () {
    var that = this;
    app.getVoice();
  },
  endstartVoice: function () {
    var that = this;
    recorderManager.stop();
    recorderManager.onStop((res) => {
      console.log('停止录音', res.tempFilePath)
      that.uploadVoice(res.tempFilePath);
      that.setData({
        tempFilePath:res.tempFilePath,
      })
    })
  },
  // 上传语音：
  uploadVoice: function (tempFilePath) {
    var that = this;
    console.log("程序进入上传语音"); 
    console.log(tempFilePath);
    wx.getStorage({
      key: 'token',
      success: function (res) {
        const token = res.data;
        const url = app.globalData.localApi + "/redpack/receiveVoice";
        console.log("上传语音url：" + url);
        console.log("上传语音filePath：" + tempFilePath);
        var userInfo = app.globalData.userInfo;
        console.log(userInfo);
        wx.uploadFile({
          url: url,
          filePath: tempFilePath,
          name: "file",
          formData: {
            "timestamp":app.timestamp(),
            "userInfo":userInfo,
            "token": token,
            "url": app.urlStr(url)
          },
          header: { "Content-Type": "multipart/form-data" },
          success: function (res) {
            console.log("请求成功");

            console.log(res)
            var result =JSON.parse(res.data);
            console.log(result)
            if (result.success){
              that.setData({
                voiceResult: true,





                
              })
            }else{
              app.showInfo(result.msg)
              console.log(result.msg);
              // if(result.msg == undefined){
              //   app.showInfo("上传语音失败！！！！！")
              // }else{
                
              // }
              
              that.setData({
                voiceResult: false,
              })
            }
          },
          fail: function (res) {
            console.log(res)
            console.log("上传失败")
            app.showInfo("网络开小差了,语音没有上传成功")
            that.setData({
              voiceResult: false,
            })
          }
        })
      },
    })
  },
  // 跳转链接
  tomyRecord:function(){
    var that = this;
    wx.navigateTo({
      url: './mRecord/myRecord',
    })

  },
  toShare:function(){
    var that = this;
    that.setData({
      clickHot: false,
    })
    console.log(that.data.houBaoStyle)
    // 正式：
    var HotStyle = that.data.houBaoStyle.toString();
    switch (HotStyle){
      case "1":
        that.iskouling();
        break;
      case "2":
        that.isqingting();
        break;
      case "3":
        that.isjuben();
        break;
    }

  },
  iskouling:function(){
    var that = this;
    console.log("执行isKouling")
    if (that.data.kouling == '') {
      app.showInfo("请设置口令");
    } else if (that.data.Money == '') {
      app.showInfo("请输入赏金");
    } else if (that.data.Number == '') {
      app.showInfo("请设置红包个数");
    } else {
      that.prepay();
    }
  },
  isqingting:function(){
    var that = this;
    console.log("执行倾听")
    console.log(that.data.voiceResult)
    if (!that.data.voiceResult){
      app.showInfo("请重新上传语音")
    } else if (that.data.Money == '') {
      app.showInfo("请输入赏金");
    } else if (that.data.Number == '') {
      app.showInfo("请设置红包个数");
    } else {
      that.prepay();
    }

  },
  isjuben:function(){
    var that = this;
    console.log("执行剧本")
    if (!that.data.voiceResult) {
      app.showInfo("请重新上传语音")
    } else if (that.data.answer==''){
      app.showInfo("请输入问题的答案")
    }else if (that.data.Money == '') {
      app.showInfo("请输入赏金");
    } else if (that.data.Number == '') {
      app.showInfo("请设置红包个数");
    } else {
      that.prepay();
    }
  },
  prepay:function(){
    console.log("执行prepay")
   
    var that = this;
    console.log(that.data.formId)
    wx.getStorage({
      key: 'token',
      success: function(res) {
        var url = app.globalData.localApi +"/redpack/prepay";
        var token = res.data;
        var timestamp = app.timestamp()
        console.log(that.data.houbaoStyle)
        wx.request({
          url: url,
          method: "POST",
          data: {
            timestamp:timestamp,
            token: token,
            url: app.urlStr(url),
            sign: Crypto.MD5(app.sign(url,token,timestamp)),
            packText:that.data.kouling,
            packMoney:that.data.Money*100,
            packCount:parseInt(that.data.Number),
            packAnswer:that.data.answer,
            packType: that.data.houBaoStyle,
            formId: that.data.formId,
          }, 
          success:function(res){
            console.log("prepay执行成功")
            console.log(res)
            that.setData({
              clickHot: true,
            })
            if(res.data.code==201){
              app.login();
            }
            if(res.data.error!==undefined){
              app.showInfo(res.data.error);
            }else if(res.data.data.payinfo==''|| res.data.data.payinfo==undefined){
              that.setData({
                orderno: res.data.data.orderinfo.orderno
              })
              wx.navigateTo({
                url: './Share/share?houBaoStyle=' + that.data.houBaoStyle
                + "&mpUrl=" + that.data.tempFilePath
                + "&Money=" + that.data.Money
                + "&Number=" + that.data.Number
                + "&kouling=" + that.data.kouling
                + "&orderno=" + that.data.orderno,
              })
            }else{
              // d微信支付；
              that.setData({
                orderno: res.data.data.orderinfo.orderno
              })
              wx.requestPayment({
                'timeStamp': res.data.data.payinfo.timeStamp.toString(),
                'nonceStr': res.data.data.payinfo.nonceStr,
                'package': res.data.data.payinfo.package,
                'signType': 'MD5',
                'paySign': res.data.data.payinfo.paySign,
                'success': function (res) {
                  console.log("支付结果")
                  console.log(res)
                  wx.navigateTo({
                    url: './Share/share?houBaoStyle=' + that.data.houBaoStyle
                    + "&mpUrl=" + that.data.tempFilePath
                    + "&Money=" + that.data.Money
                    + "&Number=" + that.data.Number
                    + "&kouling=" + that.data.kouling
                    + "&orderno=" + that.data.orderno,
                  })
                },
                'fail': function (res) {
                  console.log("支付结果")
                  console.log(res)
                }
              })
            }
          }
        })
      },
    })
   
 
  },
 
  // 获取页面填入的值
  koulingInput:function(e){
    var that = this;
    console.log(e.detail.value)
      that.setData({
        kouling: e.detail.value,
      }) 
  },
  koulingInput1: function (e) {
    var that = this;
    console.log(e.detail.value)
    var conf = app.checkChinese(e.detail.value,10);
    console.log(conf);
    if (conf) {
      that.setData({
        kouling: e.detail.value,
      })

    } else {
      app.showInfo("请输入中文口令")

    }

  },
  MoneyInput:function(e){
    var that = this;
    console.log(e.detail.value)
    var reg = new RegExp("^\\d+(\\.\\d{0,2})?$");
    if (!reg.test(e.detail.value)) {
      app.showInfo("请您输入正确的金额（只包含两位小数）")
    }else{
      that.setData({
        Money: e.detail.value,
      })
    }
   
  },
  NumberInput: function (e) {
    var that = this;
    console.log(e.detail.value)
    that.setData({
      Number: e.detail.value,
    })
  },
  jubenAnswerInput:function(e){
    var that = this;
    console.log(e.detail.value);
    that.setData({
      answer:e.detail.value,
    })
  },
  // 麦克风帧动画 
  speaking: function () {
    //话筒帧动画 
    var that = this;
    var i = 0;
    that.speakerInterval = setInterval(function () {
      i++;
      i = i % 7;
      that.setData({
        speakerUrl: that.data.speakerUrlPrefix + i + that.data.speakerUrlSuffix,
      });
      console.log("[Console log]:Speaker image changing...");
    }, 300);
  },
 
  // 页面跳转 
  tojilu:function(){
    var that = this;

  },
  totixian:function(){
    var that = this;
    wx.navigateTo({
      url: '../tixian/tixian?balance=' + that.data.balance.balance,
      // url:'./Share/sharePic'
    })
  },
  tofuli:function(){
    wx.navigateTo({
      url: '../fuli/fuli',
    })
  },
  tomine:function(){
    var that = this;
    wx.navigateTo({
      url: '../mine/mine?balance='+that.data.balance.balance,
    })
  }
})
